package servlet;

import com.fasterxml.jackson.databind.ObjectMapper;
import dao.MusicDao;
import entity.Music;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@WebServlet("/deleteSelMusicServlet")
public class DeleteSelMusicServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        req.setCharacterEncoding("utf-8");
        resp.setContentType("application/json;charset=utf-8");

        String[] sIds = req.getParameterValues("id[]");

        MusicDao musicDao = new MusicDao();

        int sum = 0;

        Map<String,Object> return_map = new HashMap<>();

        List<Music> musicList = new ArrayList<>();

        for (int i = 0; i < sIds.length; i++) {
            int id = Integer.parseInt(sIds[i]);
            Music music = musicDao.findMusicById(id);

            if(music == null) continue;
            //有当前需要删除的音乐
            int ret = musicDao.deleteMusicById(id);

            if(ret == 1) {
                //数据库删除成功，那么服务器上的数据也需要发生改变
                //删除服务器目录下的对应的文件
                /*File file = new File("D:\\项目\\Java\\mycloudmusic\\src\\main\\webapp\\"+music.getUrl()+".mp3");*/

                File file = new File("/home/zhengli/tomcat/apache-tomcat-8.5.69/webapps/mycloudmusic/"+music.getUrl()+".mp3");

                if(file.delete()) {
                    sum += ret;
                }else {
                    return_map.put("msg",false);
                    System.out.println("删除失败！");
                }
            }else {
                return_map.put("msg",false);
                System.out.println("删除失败！");
            }
        }

        if(sum == sIds.length) {
            return_map.put("msg",true);
            System.out.println("删除成功！");
        }else {
            return_map.put("msg",false);
            System.out.println("删除失败！");
        }

        ObjectMapper mapper = new ObjectMapper();
        //利用Jackson将map转化为json对象，
        // writer 将转换后的json字符串保存到字符输出流中，最后给客户端
        mapper.writeValue(resp.getWriter(),return_map);
    }
}